package orm

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"mall_book/model"
	"strings"
	"time"
)

var DB *gorm.DB

func InitGorm() error {
	var DbUser = "root"
	var DbPassword = "123456"
	var DbHost = "127.0.0.1"
	var DbPort = "3306"
	var DbName = "mall_book"
	pathRead := strings.Join([]string{DbUser, ":", DbPassword, "@tcp(", DbHost, ":", DbPort, ")/", DbName, "?charset=utf8mb4&parseTime=true"}, "")
	var ormLogger logger.Interface
	if gin.Mode() == "debug" {
		ormLogger = logger.Default.LogMode(logger.Info)
	} else {
		ormLogger = logger.Default
	}
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       pathRead,
		DefaultStringSize:         256,  //string类型默认长度
		DisableDatetimePrecision:  true, //精致datetime精度，mysql5.6之前的数据库不支持
		DontSupportRenameIndex:    true, //重命名索引，就要把索引先删除在重建，mysql5.7不支持
		DontSupportRenameColumn:   true, //用change重命名列，mysql8之前数据库不支持
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		Logger: ormLogger,
		//命名策略
		NamingStrategy: schema.NamingStrategy{
			//不加s 单数化
			SingularTable: true,
		},
	})
	if err != nil {
		return err
	}
	//数据库迁移
	db.AutoMigrate(&model.User{})
	sqlDB, _ := db.DB()
	sqlDB.SetMaxOpenConns(20) //设置连接池
	sqlDB.SetConnMaxLifetime(time.Second * 30)
	DB = db
	return nil
}
